<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!--角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" align="center">
          <template slot-scope="scope">
            <!-- 栅格布局 -->
            <el-row
              :class="['dbbottom', i1 === 0 ? 'dbtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限（5列） -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二级个三级权限（19列） -->
              <el-col :span="19">
                <!-- 通过for对一级权限遍历的到二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'dbtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 通过for循环对二级权限列表循环得到三级权限列表 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      :class="[i3 === 0 ? '' : 'dbtop']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
                {{ scope.row }}
            </pre> -->
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column
          label="序号"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="角色描述"
          prop="roleDesc"
          align="center"
        ></el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <!-- 提示信息 -->
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                square
                @click="showeditdialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <!-- 提示信息 -->
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                square
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 分配权限按钮 -->
            <!-- 提示信息 -->
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                square
                @click="showSetRightDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogclose"
    >
      <!-- 表单内容主题 -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormref"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName" disabled></el-input>
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <!-- 页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="45%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //角色列表
      rolelist: [],
      //(保存)查询到的角色信息对象
      editForm: {},
      //所有权限列表
      rightList: [],
      /*设置对话框为隐藏  */
      dialogVisible: false,

      /* 设置分配权限对话框的显示与隐藏 */
      setRightDialogVisible: false,

      /* 树形控件的属性绑定对象 */
      treeProps: {
        label: "authName",
        children: "children",
      },

      //默认选中的节点id值数组
      defkeys: [],
      //当前即将分配的权限的角色id
      roleId: "",

      //控制修改用户框的显示
      editdialogVisible: false,
      //控制分配角色对话框

      /* 添加角色的表单数据 */
      addForm: {
        roleName: "",
        roleDesc: "",
      },

      addFormrules: {
        roleName: [
          {
            required: true,
            message: "角色名称不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 6,
            message: "请输入合法长度的角色名称(1-6个字符之间)",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "角色描述不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 6,
            message: "请输入合法长度的角色名称(1-6个字符之间)",
            trigger: "blur",
          },
        ],
      },
    };
  },

  //生命周期函数
  created() {
    this.getRolesList();
  },

  methods: {
    //获取所有角色的列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.console.error("获取角色列表失败");
      } else {
        this.rolelist = res.data;
        console.log(this.rolelist);
      }
    },

    // 根据id删除对应的权限
    async removeRightById(role, rightId) {
      //弹框提示是否删除该文件，是否继续？
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除操作！");
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        );
        if (res.meta.status !== 200) {
          return this.$message.error("删除角色权限失败！");
        } else {
          this.$message.success("删除角色权限成功！");
          /* this.getRolesList(); */
          //把当前的最新数据赋值给当前角色的childred属性
          role.children = res.data;
        }
      }
    },

    //监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //监听添加角色的对话框的关闭事件
    addDialogclose() {
      this.$refs.addFormref.resetFields();
    },

    //点击确定，添加角色
    addUser() {
      this.$refs.addFormref.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        //发起添加用户数据请求
        const { data: res } = await this.$http.post("roles", {
          roleName: this.addForm.roleName,
          roleDesc: this.addForm.roleDesc,
        });
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败！");
        }

        //隐藏添加用户对话框
        this.dialogVisible = false;
        //刷新用户列表
        this.getRolesList();
        this.$message.success("添加用户成功");
        console.log(res);
      });
    },

    // 根据id删除对应的角色
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      //console.log(id);
      //如果用户确认删除，则返回值为字符串confirm
      //如果用户取消了删除，则返回值为字符串cancel
      /* console.log(confirmResult); */

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除操作！");
      } else {
        const { data: res } = await this.$http.delete("roles/" + id);
        if (res.meta.status !== 200) {
          return this.$message.error("删除角色失败！");
        } else {
          this.$message.success("删除角色成功！");
          this.getRolesList();
        }
      }
    },

    //展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id;
      //获取所有权限数据
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限数据失败！");
      }
      this.rightList = res.data; //获取到的权限数据保存到data中
      console.log(this.rightList);

      this.getLeafkeys(role, this.defkeys);

      this.setRightDialogVisible = true;
    },

    /* 这是编辑的对话用户框(根据id查询角色信息) */
    async showeditdialog(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询角色信息失败！");
      }

      this.editForm = res.data;
      /* 回调id */
      this.editForm.id = res.data.roleId;
      this.editdialogVisible = true;
      /* console.log(id); */
    },

    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        //发起修改用户数据请求
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.id,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新用户信息失败！");
        }
        //关闭对话框
        //刷新数据列表
        //提示更新成功
        this.editdialogVisible = false;
        this.getRolesList();
        this.$message.success("更新用户信息成功");
      });
    },

    //通过递归的形式，获取角色下已经选中的所有三级权限的id，并保存在下面的数组中
    getLeafkeys(node, arr) {
      //如果当前node节点不包含children属性，则就是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((element) => {
        this.getLeafkeys(element, arr);
      });
    },
    //监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defkeys = [];
    },
    //点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败！");
      } else {
        this.$message.success("分配权限成功！");
        this.getRolesList();
        this.setRightDialogVisible = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
.dbtop {
  border-top: 1px solid #eee;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>